package com.gqj.meter.controller;

import com.github.pagehelper.PageHelper;
import com.gqj.common.constant.BusinessConstants;
import com.gqj.common.core.controller.BaseController;
import com.gqj.common.core.domain.AjaxResult;
import com.gqj.common.core.domain.entity.SysDictData;
import com.gqj.common.core.domain.entity.SysDictType;
import com.gqj.common.core.domain.entity.SysUser;
import com.gqj.common.core.page.TableDataInfo;
import com.gqj.common.utils.DateUtils;
import com.gqj.common.utils.StorageUtil;
import com.gqj.common.utils.StringUtils;
import com.gqj.meter.domain.*;
import com.gqj.meter.mapper.*;
import com.gqj.meter.service.*;
import com.gqj.meter.service.impl.MdInTaskDetailsServiceImpl;
import com.gqj.system.service.ISysDictDataService;
import com.gqj.system.service.ISysDictTypeService;
import com.gqj.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 工作台硬件接口Controller
 *
 * @author lxq
 * @date lxq-03-03
 */
@Api(value = "/meter/mdWorktop", description = "工作台硬件接口Controller")
@RestController
@RequestMapping("/meter/mdWorktop")
public class MdWorktopController extends BaseController {
    @Autowired
    private IMdOutTaskService mdOutTaskService;
    @Autowired
    private IMdInTaskService mdInTaskService;
    @Autowired
    private MdInTaskDetailsServiceImpl mdInTaskDetailsService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IMdOutTaskDetailsService mdOutTaskDetailsService;
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private IMdMeterService mdMeterService;
    @Autowired
    private IMdItService mdItService;
    @Autowired
    private IMdConcentratorService mdConcentratorService;
    @Autowired
    private IMdStockPosInfoService mdStockPosInfoService;
    @Autowired
    private IMdChkTaskService mdChkTaskService;
    @Autowired
    private IMdChkTaskDetailsService mdChkTaskDetailsService;
    @Autowired
    private MdInTaskDetailsMapper mdInTaskDetailsMapper;
    @Autowired
    private MdMeterMapper mdMeterMapper;
    @Autowired
    private MdOutTaskDetailsMapper mdOutTaskDetailsMapper;
    @Autowired
    private MdItMapper mdItMapper;
    @Autowired
    private MdConcentratorMapper mdConcentratorMapper;

    /**
     * 查询员工工号
     */
    @ApiOperation("查询员工工号")
    @GetMapping("selectUserByUserName")
    public AjaxResult selectUserByUserName(String userName) {
        boolean isLogin = false;
        if (null == userName || "".equals(userName)) {
            return AjaxResult.error("员工工号为空，请检查重试！");
        }
        SysUser sysUser = sysUserService.selectUserByUserName(userName);
        if (null != sysUser) {
            isLogin = true;
        }
        return success(isLogin);
    }

    /**
     * 查询入库任务列表
     */
    @ApiOperation("查询入库任务列表")
    @PostMapping("/selectInTaskList")
    public TableDataInfo selectInTaskList(@RequestBody MdInTask mdInTask) {
        PageHelper.startPage(mdInTask.getPageNum(), mdInTask.getPageSize());
        List<MdInTask> list = mdInTaskService.selectMdInTaskList(mdInTask);
        for (MdInTask mdInTask1 : list) {
            //查询单据子表信息
            mdInTask1.setMdInTaskDetailsList(mdInTaskDetailsService.selectMdInTaskDetailsList(new MdInTaskDetails() {{
                setInTaskNo(mdInTask1.getInTaskNo());
            }}));
        }
        return getDataTable(list);
    }

    /**
     * 查询入库明细列表
     */
    @ApiOperation("查询入库明细列表")
    @GetMapping("/selectInTaskDetailsList")
    public AjaxResult selectInTaskDetailsList(@RequestBody MdInTaskDetails mdInTaskDetails) {
        List<MdInTaskDetails> list = mdInTaskDetailsService.selectMdInTaskDetailsList(mdInTaskDetails);
        return AjaxResult.success(list);
    }

    /**
     * 工作台新增入库任务(确认入库)
     */
    @ApiOperation("工作台新增入库任务(确认入库)")
    @PostMapping("/addInTask")
    public AjaxResult add(@RequestBody @Validated MdInTask mdInTask) {
        if (mdInTask.getMdInTaskDetailsList().size() == 0) {
            return AjaxResult.error("任务明细不能为空,请检查重试!");
        }
        return toAjax(mdInTaskService.insertMdInTaskWorktop(mdInTask));
    }

    /**
     * 查询出库任务列表
     */
    @ApiOperation("查询出库任务列表")
    @PostMapping("/selectOutTaskList")
    public TableDataInfo selectOutTaskList(@RequestBody MdOutTask mdOutTask) {
        PageHelper.startPage(mdOutTask.getPageNum(), mdOutTask.getPageSize());
        List<MdOutTask> list = mdOutTaskService.selectMdOutTaskList(mdOutTask);
        //查询单据子表信息
        for (MdOutTask mdOutTask1 : list) {
            mdOutTask1.setMdOutTaskDetailsList(mdOutTaskDetailsService.selectMdOutTaskDetailsList(new MdOutTaskDetails() {{
                setOutTaskNo(mdOutTask1.getOutTaskNo());
            }}));
        }
        return getDataTable(list);
    }

    /**
     * 查询出库明细列表
     */
    @ApiOperation("查询出库明细列表")
    @GetMapping("/selectOutTaskDetailsList")
    public AjaxResult selectOutTaskDetailsList(@RequestBody MdOutTaskDetails mdOutTaskDetails) {
        List<MdOutTaskDetails> list = mdOutTaskDetailsService.selectMdOutTaskDetailsList(mdOutTaskDetails);
        return AjaxResult.success(list);
    }

    /**
     * 工作台新增出库任务（确认出库）
     */
    @ApiOperation("工作台新增出库任务(确认出库)")
    @PostMapping("/addOutTask")
    public AjaxResult add(@RequestBody @Validated MdOutTask mdOutTask) {
        if (mdOutTask.getMdOutTaskDetailsList().size() == 0) {
            return AjaxResult.error("任务明细不能为空,请检查重试!");
        }
        return toAjax(mdOutTaskService.insertMdOutTaskWorktop(mdOutTask));
    }


    /**
     * 查询字典类型
     */
    @ApiOperation("查询字典类型")
    @GetMapping("/selectDictTypeList")
    public TableDataInfo selectDictTypeList(SysDictType dictType) {
        startPage();
        List<SysDictType> list = dictTypeService.selectDictTypeList(dictType);
        return getDataTable(list);
    }

    /**
     * 查询字典类型数据
     */
    @ApiOperation("查询字典类型数据")
    @GetMapping("/selectDictDataList")
    public TableDataInfo selectDictDataList(SysDictData dictData) {
        startPage();
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        return getDataTable(list);
    }

    /**
     * 查询电能表列表
     */
    @ApiOperation("查询电能表列表")
    @GetMapping("/selectMdMeterList")
    public TableDataInfo selectMdMeterList(MdMeter mdMeter) {
        startPage();
        List<MdMeter> list = mdMeterService.selectMdMeterList(mdMeter);
        return getDataTable(list);
    }

    /**
     * 查询互感器列表
     */
    @ApiOperation("查询互感器列表")
    @GetMapping("/selectMdItList")
    public TableDataInfo selectMdItList(MdIt mdIt) {
        startPage();
        List<MdIt> list = mdItService.selectMdItList(mdIt);
        return getDataTable(list);
    }

    /**
     * 查询集中器列表
     */
    @ApiOperation("查询集中器列表")
    @GetMapping("/selectMdConcentratorList")
    public TableDataInfo selectMdConcentratorList(MdConcentrator mdConcentrator) {
        startPage();
        List<MdConcentrator> list = mdConcentratorService.selectMdConcentratorList(mdConcentrator);
        return getDataTable(list);
    }

    /**
     * 查询储位信息列表
     */
    @ApiOperation("查询储位信息列表")
    @GetMapping("/selectMdStockPosInfoList")
    public TableDataInfo selectMdStockPosInfoList(MdStockPosInfo mdStockPosInfo) {
        startPage();
        List<MdStockPosInfo> list = mdStockPosInfoService.selectMdStockPosInfoList(mdStockPosInfo);
        return getDataTable(list);
    }

    /**
     * 查询盘点任务列表
     */
    @ApiOperation("查询盘点任务列表")
    @PostMapping("/selectMdChkTaskList")
    public TableDataInfo selectMdChkTaskList(@RequestBody MdChkTask mdChkTask) {
        PageHelper.startPage(mdChkTask.getPageNum(), mdChkTask.getPageSize());
        List<MdChkTask> list = mdChkTaskService.selectMdChkTaskList(mdChkTask);
        //查询单据子表信息
        for (MdChkTask mdChkTask1 : list) {
            mdChkTask1.setMdChkTaskDetailsList(mdChkTaskDetailsService.selectMdChkTaskDetailsList(new MdChkTaskDetails() {{
                setChkTaskId(mdChkTask1.getChkTaskId());
            }}));
        }
        return getDataTable(list);
    }

    /**
     * 查询盘点任务详情列表
     */
    @ApiOperation("查询盘点任务详情列表")
    @GetMapping("/selectMdChkTaskDetailsList")
    public AjaxResult selectMdChkTaskDetailsList(@RequestBody MdChkTaskDetails mdChkTaskDetails) {
        List<MdChkTaskDetails> list = mdChkTaskDetailsService.selectMdChkTaskDetailsList(mdChkTaskDetails);
        return AjaxResult.success(list);
    }

    /**
     * 工作台新增盘点任务（盘点完成）
     */
    @ApiOperation("新增盘点任务")
    @PostMapping("/addMdChkTask")
    public AjaxResult addMdChkTask(@RequestBody MdChkTask mdChkTask) {
        if (mdChkTask.getMdChkTaskDetailsList().size() == 0) {
            return AjaxResult.error("任务明细不能为空,请检查重试!");
        }
        return toAjax(mdChkTaskService.insertMdChkTaskWorktop(mdChkTask));
    }

    /**
     * 根据标签号查询物资信息
     */
    @ApiOperation("根据标签号查询物资信息")
    @PostMapping("/selectMaterialInfoByRfid")
    public AjaxResult selectMaterialInfoByRfid(@RequestBody MdSelectByRfid mdSelectByRfid) {
        String[] rfidNos = mdSelectByRfid.getRfidNos();
        // 前台无法判断类型-需要每个类型都查询
        List<MdMeter> listMeter = mdMeterService.selectMdMeterByRfidBath(rfidNos);
        if (!listMeter.isEmpty()) {
            return AjaxResult.success(listMeter);
        }
        List<MdIt> listIt = mdItService.selectMdItByRfidBath(rfidNos);
        if (!listIt.isEmpty()) {
            return AjaxResult.success(listIt);
        }
        List<MdConcentrator> listConcentrator = mdConcentratorService.selectMdConcentratorByRfidBath(rfidNos);
        if (!listConcentrator.isEmpty()) {
            return AjaxResult.success(listConcentrator);
        }

//        if (BusinessConstants.ASSETS_CATEGORY_METER.equals(mdSelectByRfid.getAssetsCategory())) {
//            List<MdMeter> listMeter = mdMeterService.selectMdMeterByRfidBath(mdSelectByRfid.getRfidNos());
//            return AjaxResult.success(listMeter);
//        } else if (BusinessConstants.ASSETS_CATEGORY_IT.equals(mdSelectByRfid.getAssetsCategory())) {
//            List<MdIt> listConcentrator = mdItService.selectMdItByRfidBath(mdSelectByRfid.getRfidNos());
//            return AjaxResult.success(listConcentrator);
//        } else if (BusinessConstants.ASSETS_CATEGORY_CONCENTRATOR.equals(mdSelectByRfid.getAssetsCategory())) {
//            List<MdConcentrator> listIt = mdConcentratorService.selectMdConcentratorByRfidBath(mdSelectByRfid.getRfidNos());
//            return AjaxResult.success(listIt);
//        }
        return AjaxResult.success(new ArrayList<>());
    }

    /*----------------后台*------------------------------------------/

    /**
     * 新增入库任务
     */
    @ApiOperation("新增入库任务")
    @PostMapping("/addInTaskInfo")
    public AjaxResult addInTaskInfo(@RequestBody MdInTask mdInTask) {
        mdInTask.setInTaskNo("RK-" + StorageUtil.getOrderNoTo12());
        mdInTaskService.insertMdInTask(mdInTask);
        MdInTask mdInTaskTem = mdInTaskService.selectMdInTaskByInTaskId(mdInTask.getInTaskId());
        return AjaxResult.success(mdInTaskTem);
    }

    /**
     * 新增入库明细
     */
    @ApiOperation("新增入库明细")
    @PostMapping("/addInTaskDetails")
    public AjaxResult addInTaskDetails(@RequestBody List<MdInTaskDetails> mdInTaskDetailsList) {
        if (StringUtils.isNull(mdInTaskDetailsList)) {
            return AjaxResult.error("明细为空，请检查重试！");
        }
        return toAjax(mdInTaskDetailsService.insertMdInTaskDetails(mdInTaskDetailsList));
    }


    /**
     * 修改入库任务状态
     */
    @ApiOperation("修改入库任务状态")
    @PostMapping("/editInTaskStatus")
    public AjaxResult editInTaskStatus(@RequestBody MdInTask mdInTask) {
        return toAjax(mdInTaskService.updateMdInTask(mdInTask));
    }

    /**
     * 新增出库任务
     */
    @ApiOperation("新增出库任务")
    @PostMapping("/addOutTaskInfo")
    public AjaxResult addOutTaskInfo(@RequestBody MdOutTask mdOutTask) {

        mdOutTaskService.insertMdOutTask(mdOutTask);
        //查询单据信息
        MdOutTask mdOutTaskTemp = mdOutTaskService.selectMdOutTaskByOutTaskId(mdOutTask.getOutTaskId());

        return AjaxResult.success(mdOutTaskTemp);
    }

    /**
     * 新增出库明细
     */
    @ApiOperation("新增出库明细")
    @PostMapping("/addOutTaskDetails")
    public AjaxResult addOutTaskDetails(@RequestBody List<MdOutTaskDetails> mdOutTaskDetailsList) {
        if (StringUtils.isNull(mdOutTaskDetailsList)) {
            return AjaxResult.error("明细为空，请检查重试！");
        }
        return toAjax(mdOutTaskDetailsService.insertMdOutTaskDetails(mdOutTaskDetailsList));
    }

    /**
     * 修改出库任务状态
     */
    @ApiOperation("修改出库任务状态")
    @PostMapping("/editOutTaskStatus")
    public AjaxResult editOutTaskStatus(@RequestBody MdOutTask mdOutTask) throws IOException, ParserConfigurationException, SAXException {
        Long outTaskId = mdOutTask.getOutTaskId();
        if (null == outTaskId) {
            return AjaxResult.error("任务主键为null，请联系系统管理员！");
        }

        String statusCode = mdOutTask.getStatusCode();
        if (null == statusCode || "".equals(statusCode)) {
            return AjaxResult.error("任务状态代码为null，请联系系统管理员！");
        }

        MdOutTask mdOutTaskTemp = mdOutTaskService.selectMdOutTaskByOutTaskId(outTaskId);

        if (statusCode.equals("2") && !mdOutTaskTemp.getStatusCode().equals("1")) {
            return AjaxResult.error("该任务不是执行中状态，无法完成！");
        }

        if (statusCode.equals("1") && !mdOutTaskTemp.getStatusCode().equals("0")) {
            return AjaxResult.error("该任务不是待执行状态，无法执行！");
        }

        mdOutTask.setAssetsCategory(mdOutTaskTemp.getAssetsCategory());
        mdOutTask.setOutTaskNo(mdOutTaskTemp.getOutTaskNo());

        if (statusCode.equals("2")) {

            mdOutTask.setOperationDate(DateUtils.getNowDate());
            //修改子表完成
            List<MdOutTaskDetails> mdOutTaskDetailsList = mdOutTaskDetailsMapper.selectMdOutTaskDetailsList(new MdOutTaskDetails() {{
                setOutTaskNo(mdOutTaskTemp.getOutTaskNo());
            }});

            for (MdOutTaskDetails mdOutTaskDetails : mdOutTaskDetailsList) {
                mdOutTaskDetails.setOperationDate(DateUtils.getNowDate());
                mdOutTaskDetails.setIsComplete(BusinessConstants.IS_COMPLETE);
                mdOutTaskDetailsMapper.updateMdOutTaskDetails(mdOutTaskDetails);
                //根据设备码判断所属类型
                String assetsCategorySelect = StorageUtil.getEquipCodeType(mdOutTaskDetails.getEquipCode());

                if (assetsCategorySelect.equals(BusinessConstants.ASSETS_CATEGORY_METER)) {
                    mdMeterMapper.updateMdMeter(new MdMeter() {{
                        setMeterId(mdOutTaskDetails.getAssetsId());
                        setServiceStatus(BusinessConstants.SERVICE_STATUS_OUT);
                    }});
                } else if (assetsCategorySelect.equals(BusinessConstants.ASSETS_CATEGORY_CONCENTRATOR)) {
                    mdConcentratorMapper.updateMdConcentrator(new MdConcentrator() {{
                        setConcentratorId(mdOutTaskDetails.getAssetsId());
                        setServiceStatus(BusinessConstants.SERVICE_STATUS_OUT);
                    }});
                } else if (assetsCategorySelect.equals(BusinessConstants.ASSETS_CATEGORY_IT)) {
                    mdItMapper.updateMdIt(new MdIt() {{
                        setItId(mdOutTaskDetails.getAssetsId());
                        setServiceStatus(BusinessConstants.SERVICE_STATUS_OUT);
                    }});
                }
            }
        }
        return toAjax(mdOutTaskService.updateMdOutTaskStatus(mdOutTask));
    }

    /**
     * 新增盘点任务
     */
    @ApiOperation("新增盘点任务")
    @PostMapping("/addchkTaskInfo")
    public AjaxResult addchkTaskInfo(@RequestBody MdChkTask mdChkTask) {
        if (StringUtils.isEmpty(mdChkTask.getAssetsCategory())) {
            return AjaxResult.error("资产大类不能为空，请检查重试");
        }
        if (StringUtils.isEmpty(mdChkTask.getCheckRange())) {
            return AjaxResult.error("盘点范围不能为空，请检查重试！");
        }
        mdChkTaskService.insertMdChkTask(mdChkTask);
        MdChkTask mdChkTaskTem = mdChkTaskService.selectMdChkTaskByChkTaskId(mdChkTask.getChkTaskId());
        return AjaxResult.success(mdChkTaskTem);
    }

    /**
     * 开始盘点
     */
    @ApiOperation("开始盘点")
    @GetMapping(value = "/startCheck/{chkTaskIds}")
    public AjaxResult startCheck(@PathVariable("chkTaskIds") Long[] chkTaskIds) {
        if (chkTaskIds.length == 0) {
            return AjaxResult.error("未获取到盘点单据信息，请检查重试");
        }

        for (int i = 0; i < chkTaskIds.length; i++) {
            MdChkTask mdChkTask = mdChkTaskService.selectMdChkTaskByChkTaskId(chkTaskIds[i]);
            if ("03".equals(mdChkTask.getStatusCode())) {
                return AjaxResult.error("单据" + mdChkTask.getChkTaskId() + "已经盘点结束，无法开始盘点");
            } else if ("02".equals(mdChkTask.getStatusCode())) {
                return AjaxResult.error("单据" + mdChkTask.getChkTaskId() + "盘点中，无法开始盘点");
            }
        }
        return toAjax(mdChkTaskService.startCheck(chkTaskIds));
    }

    /*
     * 结束盘点
     * */
    @ApiOperation("结束盘点")
    @PostMapping("/endCheck")
    public AjaxResult endCheck(@RequestBody MdChkTask mdChkTask) {
        Long chkTaskId = mdChkTask.getChkTaskId();
        if (null == chkTaskId || chkTaskId == 0) {
            return AjaxResult.error("任务ID为空，请联系系统管理员！");
        }
        MdChkTask chkTask = mdChkTaskService.selectMdChkTaskByChkTaskId(chkTaskId);
        if (null == chkTask) {
            return AjaxResult.error("任务不存在，请联系系统管理员！");
        }
        if (!"02".equals(chkTask.getStatusCode())) {
            return AjaxResult.error("任务不是执行中状态，无法修改明细！");
        }
        mdChkTask.setUseEquipment("02");
        mdChkTask.setAssetsCategory(chkTask.getAssetsCategory());
        mdChkTask.setStatusCode("03");
        mdChkTask.setChkDate(DateUtils.getNowDate());
        return toAjax(mdChkTaskService.checkMdChkTask(mdChkTask));
    }

    /**
     * 获取资产统计信息
     */
    @ApiOperation("获取资产统计信息")
    @GetMapping("/getMaterialStatisticsInfo/{curStatusCode}")
    public AjaxResult getMaterialStatisticsInfo(@PathVariable String curStatusCode) {
        List<Map<String, Object>> map = mdMeterService.getMaterialStatisticsInfo(curStatusCode);
        return success(map);
    }
}
